package org.company.mars.zookeeper.monitor;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.company.mars.zookeeper.monitor.DataMonitor.DataMonitorListener;

public class StatListener implements DataMonitorListener {
    
    private Process child;
    
    private String filename;
    
    private String[] exec;
    
    public StatListener(String filename,String[] exec) {
        this.filename = filename;
        this.exec = exec;
    }

    @Override
    public void reboot(byte[] data) {
        if(data == null) {
            System.out.println("Killing process");
            this.shutdown();
            return;
        }
        
        //关闭子进程
        this.shutdown();
        
        try {
            IOUtils.copy(new ByteArrayInputStream(data), new FileOutputStream(filename));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("starting child process");
        try {
            child = Runtime.getRuntime().exec(exec);
            System.out.println("child pid == " + child);
            IOUtils.copy(child.getInputStream(), System.out);
            IOUtils.copy(child.getErrorStream(), System.err);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private void shutdown() {
        if(this.child == null) {
            return;
        }
        System.out.println("Stopping child process");
        this.child.destroy();
        try {
            this.child.waitFor();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void closing(int rc) {
        // TODO Auto-generated method stub
        synchronized (this) {
            notifyAll();
        }
    }

}
